<template>
  <div class="app-page">
    <div class="content">
      <el-card class="left">
        <div slot="header" class="clearfix">
          <span>机构</span>
        </div>
        <el-tree
          ref="tree"
          node-key="id"
          highlight-current
          :data="orgList"
          :props="defaultProps"
          @current-change="handleTreeSelected"
        />
      </el-card>

      <el-card class="right">
        <div slot="header" class="clearfix">
          <span>人员</span>
        </div>
        <table-search
          ref="tableSearch"
          label-width="80px"
          :search-form="searchFormItem"
          :on-submit="handleQuery"
          :on-reset="handleQuery"
        />
        <el-card>
          <div class="app-table-action-wrap">
            <auth-button
              auth-key="d_4_1"
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
            >
              新增
            </auth-button>
            <auth-button
              auth-key="d_4_6"
              size="small"
              @click="handleDownloadTemp"
            >
              下载导入模板
            </auth-button>

            <auth-button
              component-name="upload"
              auth-key="d_4_7"
              class="upload-btn"
              :action="uploadUrl"
              :show-file-list="false"
              :limit="1"
              :before-upload="handleBeforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
            >
              <auth-button
                auth-key="d_4_7"
                size="small"
              >
                导入
              </auth-button>
            </auth-button>
            <auth-button
              auth-key="d_4_8"
              size="small"
              @click="handleExport"
            >
              导出
            </auth-button>
          </div>

          <table-paging
            :table-list="tableList"
            :table-column="tableColumn"
            :table-paging="tablePaging"
            :table-total="tableTotal"
            :table-btn-width="240"
            @pagingChange="handlePaginChange"
          />
        </el-card>
      </el-card>
    </div>

    <account-update
      ref="update"
      :title="dialogTitle"
      :dept-list="deptDropList"
      :visible.sync="dialogVisible"
      :is-hide-buttons="isHideButtons"
      @handleModalSubmit="handleModalSubmit"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fetchOrgFindPage } from '@/api/basicinfo/system/organization'
import { fetchDropDeptAllList, fetchDropDictionaryList } from '@/api/common/commonDropDown'
import { fetchAccountFindPage, fetchAccountGet, fetchAccountAdd, fetchAccountUpdate, fetchAccountDelete,
  fetchAccountStatusUpdate, fetchAccountExport, fetchResetPassword, fetchDownloadTemplate, AccountImportUrl } from '@/api/basicinfo/basicdata/account'
import { createTreeList } from '@/utils'
import { TableSearch, TablePaging, AuthButton } from '@/components'
import { searchFormItem, tableColumn } from './config'
import AccountUpdate from './update'

export default {
  name: 'Account',
  components: { TableSearch, TablePaging, AccountUpdate, AuthButton },
  data() {
    return {
      orgList: [], // 机构列表
      deptDropList: [], // 部门下拉

      defaultProps: {
        children: 'children',
        label: 'orgName'
      },

      selectedOrgId: 0,

      searchFormItem: searchFormItem(),
      searchFormData: {},

      tableList: [],
      tableColumn: tableColumn(this.handleEdit, this.handleStart, this.handleDelete, this.handleResetPassword),
      tableTotal: 0,
      tablePaging: {
        page: 1,
        pagesize: 10
      },

      dialogTitle: '新增',
      dialogVisible: false,

      uploadUrl: ''
    }
  },
  computed: {
    ...mapGetters(['userOrgId']),
    isHideButtons() {
      return this.userOrgId !== this.selectedOrgId
    }
  },
  created() {
    this.postOrgFindPage()
  },
  methods: {
    handleTreeSelected(data, node) { // 机构选中
      this.selectedOrgId = data.id
      this.searchFormData = {
        ...this.searchFormData,
        orgId: this.selectedOrgId
      }
      this.uploadUrl = AccountImportUrl + '?orgId=' + this.selectedOrgId
      this.postFindPage()
      this.postDeptAllList(this.selectedOrgId)
    },

    handleQuery(values) { // 查询点击
      if (!this.selectedOrgId) {
        this.$message.warning('请先选择机构!')
        return false
      }
      this.searchFormData = {
        ...this.searchFormData,
        ...values
      }
      this.tablePaging = {
        page: 1,
        pagesize: 10
      }
      this.postFindPage()
    },

    handleAdd() { // 添加
      this._checkOrg() && this._setModalData()
    },

    handleDownloadTemp() { // 下载模板
      fetchDownloadTemplate()
    },

    handleResetPassword(id) { // 重置密码
      this._checkOrg() && this.postResetPassword(id)
    },

    handleUploadSuccess(res) { // 导入成功
      if (res.code === 0) {
        this.$messsage.success('导入成功!')
        this.postFindPage()
        return false
      }
      this.$message.warning(res.message)
    },

    handleUploadError() { // 导入失败
      this.$messsage.success('导入失败!')
    },

    handleBeforeUpload() {
      if (!this.selectedOrgId) {
        this.$message.warning('请先选择机构!')
        return false
      }
    },

    handleExport() { // 导出
      if (!this.selectedOrgId) {
        this.$message.warning('请先选择机构!')
        return false
      }
      fetchAccountExport({ ...this.$refs.tableSearch.formValue, orgId: this.selectedOrgId })
    },

    handleEdit(id) { // 修改
      this.postGet(id)
    },

    handleStart(id, status) { // 开启
      this._checkOrg() && this.postStatusUpdate(id, status)
    },

    handleDelete(id) { // 删除
      this._checkOrg() && this.postDelete(id)
    },

    handleModalSubmit(values) { // 弹窗提交
      if (values.id) {
        this.postUpdate(values)
        return false
      }
      values.orgId = this.selectedOrgId
      this.postAdd(values)
    },

    hanleClose() { // 弹窗关闭
      this.dialogVisible = false
    },

    handlePaginChange(pageInfo) { // 分页改变
      this.tablePaging = pageInfo
      this.postFindPage()
    },

    _checkOrg() { // 判断操作的是否跟用户一样的机构
      if (!this.selectedOrgId) {
        this.$message.warning('请先选择机构!')
        return false
      }
      if (this.selectedOrgId !== this.userOrgId) {
        this.$message.warning('不允许操作其他机构数据')
        return false
      }
      return true
    },

    _setModalData(title = '新增', visible = true, modalFormData = { orgId: this.selectedOrgId }) { // 设置弹窗
      this.$refs.update.modalFormData = this.formatModalFormData(modalFormData)
      this.dialogTitle = title
      this.dialogVisible = visible
    },

    formatModalFormData(data) { // 修改时格式化数据
      const { deviceIdStr, insuranceType } = data
      data.deviceIdList = deviceIdStr ? deviceIdStr.split(',') : []
      data.insuranceTypeList = insuranceType ? insuranceType.split(',') : []
      return data
    },

    postFindPage() { // 查询数据
      fetchAccountFindPage({ ...this.searchFormData, ...this.tablePaging })
        .then((res) => {
          const { records, current, size, total } = res
          this.tableList = records
          this.tablePaging = {
            page: current,
            pagesize: size
          }
          this.tableTotal = total
        })
    },

    postAdd(values) { // 添加
      fetchAccountAdd(values).then(res => {
        this.dialogVisible = false
        this.$message.success('新增成功')
        this.postFindPage()
      })
    },

    postGet(id) { // 获取详情
      fetchAccountGet({ id }).then(res => {
        this._setModalData('修改', true, res)
      })
    },

    postUpdate(values) { // 更新
      fetchAccountUpdate(values).then(() => {
        this.dialogVisible = false
        this.$message.success('修改成功')
        this.postFindPage()
      })
    },

    postStatusUpdate(id, status) { // 开启
      fetchAccountStatusUpdate({ id, status }).then(() => {
        this.$message.success('修改成功')
        this.postFindPage()
      })
    },

    postResetPassword(id) { // 重置密码
      fetchResetPassword({ id }).then(() => {
        this.$message.success('操作成功!')
      })
    },

    postDelete(id) { // 删除
      fetchAccountDelete({ id }).then(() => {
        this.$message.success('删除成功')
        this.postFindPage()
      })
    },

    postOrgFindPage() { // 获取机构列表
      fetchOrgFindPage().then(res => {
        this.orgList = createTreeList(res.records)
      })
    },

    postDeptAllList(orgId) { // 部门下拉
      fetchDropDeptAllList({ orgId }).then(res => {
        this.deptDropList = res.map(e => ({ key: e.id, value: e.name }))
        this.searchFormItem = searchFormItem(this.deptDropList)
      })
    },

    postDropList(groupName, result) { // 数据字典下拉
      fetchDropDictionaryList({ groupName }).then(res => {
        result = res.map(e => ({ key: e.id, value: e.dicValue }))
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-page {
  .content {
    min-height: calc(100vh - 132px);
    display: flex;
    justify-content: flex-start;

    .upload-btn {
      display: inline-block;
    }

    .left {
      min-width: 240px;
    }
    .right {
      width: 100%;
      box-sizing: border-box;
      overflow: auto;
    }

    .table {
      clear: both;
      width: 100%;
    }

    .title {
      margin-top: 20px;
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 20px;
    }
  }
}
</style>
